#ifndef SERVER_H_
#define SERVER_H_

#include <string>
#include <vector>
#include <queue>
#include <deque>

#include <boost/thread.hpp>
#include <protocol/TBinaryProtocol.h>
#include <server/TThreadedServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>

#include "thrift/CrawlerServer.h"
#include "store.h"
#include "parser.h"
#include "config.h"
#include "url.h"

using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using boost::shared_ptr;

namespace crawler { namespace server {
class CrawlerServerHandler : virtual public CrawlerServerIf {
 public:
  const static size_t kPoolSize = 4096;
  CrawlerServerHandler(Store *store, const Config *config);
  void GetDownloadUrl(std::string& _return);
  void GetStoredPage(Page& _return, const std::string& url);
  void SendPage(const Page& page);
  void GetProgress(Progress& _return);
  void Stop();
  void CheckStop();

 private:
  bool stop_;
  Store *store_;
  std::string homepage_;
  std::deque<std::string> url_pool_;
  boost::mutex mutex_;
  const Config *config_;
};

class Server {
 public:
  Server(const Config *config);
  void operator()();
  void Start();
  void Stop();
  void Join();

 protected:
  shared_ptr<boost::thread>         thread_;
  shared_ptr<TThreadedServer>       server_;
  shared_ptr<CrawlerServerHandler>  handler_;
  const Config                     *config_;
  shared_ptr<Store>                 store_;
};
}}

#endif

